﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.Administration;

namespace MicrosoftWebAdministration.WindowsFormsApp
{
    /// <summary>
    /// 快速添加网站
    /// </summary>
    public partial class FormStartup : Form
    {
        /// <summary>
        /// 初始化快速添加网站
        /// </summary>
        public FormStartup()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 创建按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCreate_Click(object sender, EventArgs e)
        {
            errorProvider1.Tag = false;
            var appPool = textBoxAppPool.Text;
            var siteName = textBoxSiteName.Text;
            var port = (ushort)numericUpDownPort.Value;
            var baseDirectory = textBoxBaseDirectory.Text;
            var name = textBoxName.Text;
            var autoCreateAppPool = checkBoxAutoCreateAppPool.Checked;
            var autoCreateDirectory = checkBoxAutoCreateDirectory.Checked;

            if (!string.IsNullOrWhiteSpace(name))
            {
                siteName = string.Format(textBoxSiteName.Text, name);
            }

            if (string.IsNullOrWhiteSpace(siteName))
            {
                errorProvider1.SetError(textBoxSiteName, "请填写网站名称。");
                errorProvider1.Tag = true;
            }

            if (string.IsNullOrWhiteSpace(appPool))
            {
                appPool = siteName;
            }

            if (string.IsNullOrWhiteSpace(appPool))
            {
                errorProvider1.SetError(textBoxAppPool, "请填写应用程序池名称。");
                errorProvider1.Tag = true;
            }

            if (port == 0)
            {
                errorProvider1.SetError(numericUpDownPort, "请填写端口号。");
                errorProvider1.Tag = true;
            }

            var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            var activeTcpListeners = ipGlobalProperties.GetActiveTcpListeners();
            if (Array.Exists(activeTcpListeners, r => r.Port == port))
            {
                errorProvider1.SetError(numericUpDownPort, "端口号已经被占用。");
                errorProvider1.Tag = true;
            }

            var tcpConnectionInformationArray = ipGlobalProperties.GetActiveTcpConnections();
            if (Array.Exists(tcpConnectionInformationArray, r => r.LocalEndPoint.Port == port))
            {
                errorProvider1.SetError(numericUpDownPort, "端口号已经被占用。");
                errorProvider1.Tag = true;
            }

            if (string.IsNullOrWhiteSpace(baseDirectory))
            {
                errorProvider1.SetError(textBoxBaseDirectory, "请填写基础目录。");
                errorProvider1.Tag = true;
            }

            if (errorProvider1.Tag.Equals(true))
            {
                return;
            }

            var physicalPath = baseDirectory;

            if (!string.IsNullOrWhiteSpace(name))
            {
                physicalPath = Path.Combine(baseDirectory, name);
            }

            if (!Directory.Exists(physicalPath))
            {
                if (autoCreateDirectory)
                {
                    Directory.CreateDirectory(physicalPath);
                }
                else
                {
                    MessageBox.Show(this, @"指定站点目录不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            using (var serverManager = new ServerManager())
            {
                if (serverManager.ApplicationPools[appPool] == null)
                {
                    if (autoCreateAppPool)
                    {
                        if (serverManager.ApplicationPools.AllowsAdd)
                        {
                            serverManager.ApplicationPools.Add(appPool);
                        }
                        else
                        {
                            MessageBox.Show(this, @"应用程序池不存在且不允许创建！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                    }
                    else
                    {
                        MessageBox.Show(this, @"应用程序池不存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                if (serverManager.Sites[siteName] != null)
                {
                    MessageBox.Show(this, @"网站已经存在！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                if (!serverManager.Sites.AllowsAdd)
                {
                    MessageBox.Show(this, @"不允许添加网站！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var site = serverManager.Sites.Add(siteName, physicalPath, port);
                foreach (var siteApplication in site.Applications)
                {
                    siteApplication.ApplicationPoolName = appPool;
                }

                serverManager.CommitChanges();
                MessageBox.Show(this, @"创建网站成功！", @"提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        /// <summary>
        /// 基础目录选择按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonBaseDirectory_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialogBaseDirectory.ShowDialog(this) == DialogResult.OK)
            {
                textBoxBaseDirectory.Text = folderBrowserDialogBaseDirectory.SelectedPath;
            }
        }
    }
}
